var express = require("express")
var http = require("http")
var mysql = require("mysql")
var bodyParser = require("body-parser")
var moment = require("moment")
// var ejs = require('ejs')
var jwt = require("jsonwebtoken")
var app = express()
// app.set('view engine','ejs')
app.use(bodyParser.urlencoded({ extended: false }))
 
// parse application/json
app.use(bodyParser.json())
    var connection = mysql.createConnection({
        host:'localhost',
        user:'root',
        password:'123456',
        timezone:'08:00',
        database:'gerenwangzhan'
    })
    connection.connect()
    app.all('*', function(req, res, next) {
        res.header('Access-Control-Allow-Origin','*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST');  
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,token');  
        res.setHeader("Content-Type", "application/json;charset=utf-8"); 
        next();
    });
    app.get('/',function(req,res){
        res.end('主页')
    })
    app.get('/user',function(req,res){
        connection.query('select * from user',function(err,data){
           res.end(JSON.stringify(data))
        })
    })
    app.get('/jilu',function(req,res){
        connection.query('select * from jilu order by id desc limit 0,3',function(err,data){
            res.end(JSON.stringify(data))
        })
    })
    app.post('/jilu',function(req,res){
        //res.write(JSON.stringify(req.body))
        connection.query('select count(*) from jilu',function(err,data){
            //res.write(JSON.stringify(data[0]))
            //@params:data 数据总条数
            //@parmas:allPageSize 数据总页数
            //@parmas:startNum 分页起始条目
            //@parmas:stopNum 分页结束条目

            var allPageSize = Math.ceil(data[0]['count(*)']/parseInt(req.body.pageSize))
            var resData ={
                allPageSize
            }
            //res.write(allPageSize.toString())
            startNum = (parseInt(req.body.pageNum)-1)*parseInt(req.body.pageSize)
            stopNum = parseInt(req.body.pageSize)
            //res.write(startNum.toString())
            connection.query('select * from jilu limit '+startNum +','+stopNum,function(err,paginationData){
                resData.data = paginationData
                res.end(JSON.stringify(resData)) 
            })
        })
    })
    app.post('/addJiLu',function(req,res){
        var token = req.headers.token
        // console.log(token)
        var username = jwt.verify(token,'token')
         var timestamp = moment().format('YYYY-MM-DD hh:mm:ss')
         connection.query('select count(*) from user where name="'+token+'"',function(err,data){
            if(data = 1){
        connection.query('insert into jilu values(null,?,?)',[req.body.jiluContent,timestamp],function(err,data){
            res.end('发表成功')
        })
        }else{
            res.end('没有权限')
        }
    })
    })
     app.get('/pages',function(req,res){
         connection.query('select id,title from pages order by id desc limit 0,4',function(err,data){
            res.end(JSON.stringify(data))
        })
     })
     app.post('/pages',function(req,res){
        connection.query('select count(*) from pages',function(err,data){
            //res.write(JSON.stringify(data[0]))
            //@params:data 数据总条数
            //@parmas:allPageSize 数据总页数
            //@parmas:startNum 分页起始条目
            //@parmas:stopNum 分页结束条目

            var allPageSize = Math.ceil(data[0]['count(*)']/parseInt(req.body.pageSize))
            var resData ={
                allPageSize
            }
            //res.write(allPageSize.toString())
            startNum = (parseInt(req.body.pageNum)-1)*parseInt(req.body.pageSize)
            stopNum = parseInt(req.body.pageSize)
            //res.write(startNum.toString())
            connection.query('select id,title from pages limit '+startNum +','+stopNum,function(err,paginationData){
                resData.data = paginationData
                res.end(JSON.stringify(resData)) 
            })
        })
     })
     app.post('/addPage',function(req,res){
        var token = req.headers.token
        // console.log(token)
        var username = jwt.verify(token,'token')
         var timestamp = moment().format('YYYY-MM-DD hh:mm:ss')
         connection.query('select count(*) from user where name="'+token+'"',function(err,data){
            if(data = 1){
                connection.query('insert into pages values(null,?,?,?)',[req.body.pageTitle,req.body.pageContent,timestamp],function(err,data){
            res.end('发表成功')
        })
            }else{
                res.end('没有权限')
            }
         })
        
    })
     app.get('/pageInfo/:id',function(req,res){
        connection.query('select * from pages where id='+req.params.id,function(err,data){
            res.end(JSON.stringify(data))
        })
     })
     app.post('/adminLogin',function(req,res){
        var body = req.body
        console.log(body)
        var username = req.body.username
        console.log(username)
        connection.query('select password from user where name="'+username+'"',function(err,data){
            console.log(data)
             if(data[0].password === req.body.password){
                var token = jwt.sign(username,'token')
                res.json({status:200,token})
                
            }else{
                res.json({status:403})
            }
        })
        
    app.post('/userToken',function(req,res){
        var token = req.headers.token
        // console.log(token)
        var username = jwt.verify(token,'token')
        console.log(username)
        connection.query('select * from user where name="'+username+'"',function(err,data){
            res.end(JSON.stringify(data))
        })
    })
             })

app.listen(3000,function(err,suc){})
